package com.group.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.group.dao.TbUserMapper;
import com.group.pojo.Common;
import com.group.pojo.TbUser;
import com.group.pojo.TbUserExample;
import com.group.pojo.TbUserExample.Criteria;
import com.group.pojo.TbUserRole;
import com.group.service.CommonService;
import com.group.service.UserRoleService;
import com.group.service.UserService;
import com.group.util.CommonUtil;
import com.group.util.MD5;

@Service
public class UserServiceImpl implements UserService{

	@Autowired
	private TbUserMapper userMapper;
	@Autowired
	private CommonService commonService;
	@Autowired
	private UserRoleService userRoleService;
	
	
	private void setCondition(Criteria criteria, TbUser user) {
		
		String id = user.getId();
		if (id != null && !"".equals(id)) {
			criteria.andIdEqualTo(id);
		}
		
		String userPassword = user.getUserPassword();
		if (userPassword != null && !"".equals(userPassword)) {
			criteria.andUserPasswordEqualTo(MD5.encrypt(userPassword));
		}
		
		String userStatus = user.getUserStatus();
		if (userStatus != null && !"".equals(userStatus)) {
			criteria.andUserStatusEqualTo(userStatus);
		}
		
		String userId = user.getUserId();
		if (userId != null && !"".equals(userId)) {
			criteria.andUserIdEqualTo(userId);
		}
		
		String loginName = user.getLoginName();
		if (loginName != null && !"".equals(loginName)) {
			criteria.andLoginNameEqualTo(loginName);
		}
		
		String userMobile = user.getUserMobile();
		if (userMobile != null && !"".equals(userMobile)) {
			criteria.andUserMobileEqualTo(userMobile);
		}
		
		String userEmail = user.getUserEmail();
		if (userEmail != null && !"".equals(userEmail)) {
			criteria.andUserEmailEqualTo(userEmail);
		}
	}
	
	
	public Map<String, String> login(HttpServletRequest request, TbUser user) {
		TbUserExample example = new TbUserExample();
		example.createCriteria().andLoginNameEqualTo(user.getLoginName());
		
		List<TbUser> legals = userMapper.selectByExample(example);
		if (legals.size() == 0) {
			Map<String, String> map = CommonUtil.getReturnMap("success", "false");
			map.put("message", "用户名或密码错误");
			return map;
		}
		
		TbUser legal = legals.get(0);
		//检查是否已经过期
		Date now = new Date();
		Date expire = legal.getPasswordExpire();
		String expireTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(expire);
		if (now.after(expire)) {
			Map<String, String> map = CommonUtil.getReturnMap("success", "false");
			map.put("message", "该账号在"+expireTime+"已经过期，请联系管理员重置密码");
			return map;
		}
		
		//检查是否已经禁用
		String userStatus = legal.getUserStatus();
		if (userStatus!=null && "0".equals(userStatus)) {
			//已经禁用
			Map<String, String> map = CommonUtil.getReturnMap("success", "false");
			map.put("message", legal.getUserName()+"在"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(legal.getUpdateTime())+"时间已经被禁用，无法登录系统");
			return map;
		}
		//登录成功
		//把登录信息放到session中
		if (null != user) {
			String password = legal.getUserPassword();
			String encrypt = MD5.encrypt(user.getUserPassword());
			if (password.equals(encrypt)) {
				request.getSession().setAttribute("USER_SESSION", legal);
				//更新用户登录信息，登录成功
				Map<String, String> map = updateLoginMsg(legal, true);
				return map;
			}
		}
		//更新用户登录信息(登录失败)，自定义方法
		Map<String, String> map = updateLoginMsg(legal, false);
		return map;
	}
	
	//更新用户登录信息
	private Map<String, String> updateLoginMsg(TbUser user, boolean isIllegal) {
		TbUser record = new TbUser();
		record.setId(user.getId());
		if (true == isIllegal) {
			//更新最近登录时间
			record.setLastLoginTime(new Date());
			record.setLoginCount(user.getLoginCount()+1);
		} else {
			//登录失败
			record.setLastLoginFailedTime(new Date());
			record.setLoginFailedCount(user.getLoginFailedCount()+1);
		}
		int update = userMapper.updateByPrimaryKeySelective(record);
		
		Map<String, String> map = CommonUtil.getReturnMap("success", "false");
		if (1 == update) {
			if (true == isIllegal) {
				map.put("success", "true");
			} else {
				map.put("message", "用户名或密码错误");
			}
		} else {
			map.put("message", "登录更新信息出错，请联系管理员");
		}
		return map;
	}

	public TbUser getLoginUser(HttpServletRequest request) throws Exception {
		TbUser user = (TbUser) request.getSession().getAttribute("USER_SESSION");
		
		//日期格式化
		String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(user.getPasswordExpire());
		user.setPasswordExpireTime(time);
		return user;
	}

	public List<TbUser> query(TbUser user) {
		TbUserExample example = new TbUserExample();
		
		setCondition(example.createCriteria(), user);
		
		List<TbUser> users = userMapper.selectByExample(example);
		return users;
	}


	public String getUserNameById(String id) {
		TbUser user = userMapper.selectByPrimaryKey(id);
		String userName = user.getUserName();
		return userName;
	}

	@Override
	public String userCheckRepect(TbUser user) {
		TbUserExample example = new TbUserExample();
		Criteria criteria = example.createCriteria().andUserStatusEqualTo("1");
		
		setCondition(criteria, user);
		
		int count = userMapper.countByExample(example);
		if (count != 0) {
			return "false";//存在此人,userId不合法
		}
		return "true";//不存在此人，数据可以添加
	}

	@Override
	public Map<String, String> save(HttpServletRequest request, TbUser user) {
		TbUser loginUser = (TbUser) request.getSession().getAttribute("USER_SESSION");

		Date date = new Date();
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.add(calendar.DATE, 90);
		Date expire = calendar.getTime();
		
		//设置创建人、创建时间
		user.setCreateUserId(loginUser.getId());
		user.setCreateTime(date);
		
		//密码
		user.setPasswordType("1");//系统初始密码
		user.setUserPassword(MD5.encrypt("123456"));
		user.setPasswordExpire(expire);
		
		//杂项
		String nextId = commonService.getTbCurrentDateNextId(new Common("tb_user", CommonUtil.getCurrentDate("yyyyMMdd")));
		user.setId(nextId);
		user.setUserStatus("1");
		user.setLoginCount(0);
		user.setLoginFailedCount(0);
		
		//提交到数据库
		int insert = userMapper.insertSelective(user);
		Map<String, String> returnMap = CommonUtil.getReturnMap("success", "false");
		
		if (insert == 1) {
			returnMap.put("success", "true");
		}
		
		// 角色信息的保存
		TbUserRole userRole = new TbUserRole();
		userRole.setRoleIds(user.getRoleIds());
		userRole.setUserId(user.getId());
		Map<String, String> save = userRoleService.save(request, userRole);
		
		returnMap.putAll(save);
		
		return returnMap;
	}

	@Override
	public Map<String, String> update(TbUser user, HttpServletRequest request) {
		//设置更新人、更新时间
		HttpSession session = request.getSession();
		Object attribute2 = session.getAttribute("USER_SESSION");
		Object attribute = attribute2;
		TbUser loginUser = (TbUser) attribute;
		user.setUpdateUserId(loginUser.getId());
		user.setUpdateTime(new Date());
		
		TbUserExample example = new TbUserExample();
		
		Criteria criteria = example.createCriteria();
		criteria.andIdEqualTo(user.getId());//是必须拥有id的，以id更新
		
		String userPassword = user.getUserPassword();
		if(userPassword != null && !"".equals(userPassword)) {
			user.setUserPassword(MD5.encrypt(userPassword));
		}
		
		
		int update = userMapper.updateByPrimaryKeySelective(user);
		
		Map<String, String> returnMap = CommonUtil.getReturnMap("success", "false");
		if (update == 1) {
			
			//更新session
			request.getSession();
			TbUser userSession = (TbUser) session.getAttribute("USER_SESSION");
			TbUserExample sessionExample = new TbUserExample();
			sessionExample.createCriteria().andIdEqualTo(userSession.getId());
			TbUser newUserSession = userMapper.selectByExample(sessionExample).get(0);
			session.setAttribute("USER_SESSION", newUserSession);
			returnMap.put("success", "true");
		}
		return returnMap;
	}

	private Map<String, String> batchOperate(String[] userIds, String userStatus,  HttpServletRequest request) {
		TbUser recode = new TbUser();
		recode.setUserStatus(userStatus);
		//设置更新人、更新时间
		TbUser loginUser = (TbUser) request.getSession().getAttribute("USER_SESSION");
		recode.setUpdateUserId(loginUser.getId());
		recode.setUpdateTime(new Date());
		
		Map<String, String> map = CommonUtil.getReturnMap("success", "true");
		for (String userId : userIds) {
			recode.setId(userId);
			int update = userMapper.updateByPrimaryKeySelective(recode);
			if (update != 1) {
				map.put("success", "false");
			}
		}
		return map;
	}

	@Override
	public Map<String, String> batchDelete(String[] userIds, HttpServletRequest request) {
		Map<String, String> map = batchOperate(userIds, "0", request);
		return map;
	}


	@Override
	public Map<String, String> batchRemoveForbidden(String[] userIds, HttpServletRequest request) {
		Map<String, String> map = batchOperate(userIds, "1", request);
		return map;
	}
	
	

}
